<template>
    <Popup ref="popupRef" :title="modeTitle" :rules="rules" :formData="formData" :width="650" @submit="handleSubmit"
        @cancel="handleCancel">
        <template #default="{ formData }">

            <div class="flex justify-center items-center p-4">
                <a-avatar :size="100" :src="formData.avatar" trigger-type="mask">

                    <img alt="avatar" src="https://dummyimage.com/300.png" />
                    <template #trigger-icon>
                        <div class="flex justify-center items-center">
                            <div class="">
                                <IconEdit />
                            </div>
                            <div class="w bg-blue-500">
                                <IconEdit />
                            </div>
                        </div>
                    </template>
                </a-avatar>
            </div>

            <a-divider dashed> 账号信息</a-divider>
            <a-row>
                <a-col :span="12">
                    <a-form-item label="管理员名称" field="username">
                        <a-input v-model="formData.username" placeholder="请输入管理员名称" :autocomplete="'new-password'" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="昵称" field="nickname">
                        <m-form-input v-model="formData.nickname" placeholder="请输入管理员昵称" />
                    </a-form-item>
                </a-col>
            </a-row>
            <a-form-item label="角色" field="role">
                <a-select multiple clearable :autocomplete="'new-password'" v-model="formData.role"
                    :options="roleOptions" placeholder="请选择角色" />
            </a-form-item>


            <a-row>
                <a-col :span="12">
                    <a-form-item label="管理员密码" field="password">
                        <a-input-password v-model="formData.password" placeholder="请输入管理员密码"
                            :autocomplete="'new-password'" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="确认密码" field="repassword">
                        <a-input-password v-model="formData.repassword" placeholder="请输入管理员密码"
                            :autocomplete="'new-password'" />
                    </a-form-item>
                </a-col>


            </a-row>


            <a-form-item label="状态" field="status">
                <a-switch v-model="formData.status" />
            </a-form-item>
            <a-row>
                <a-col :span="12">

                </a-col>
            </a-row>

            <a-divider dashed> 组织架构 </a-divider>


            <a-form-item label="所属组织" field="organization_id">
                <a-select :options="organizeOptions" v-model="formData.organization_id" placeholder="请选择组织架构"
                    @change="handleDepartmentChange" />
            </a-form-item>

            <a-row>
                <a-col :span="12" v-if="formData.organization_id">
                    <a-form-item label="所属部门" field="department_id">
                        <a-select :options="departmentOptions" v-model="formData.department_id"
                            @change="handlePositionChange" />
                    </a-form-item>
                </a-col>

                <a-col :span="12" v-if="formData.department_id">
                    <a-form-item label="职位" field="position_id">
                        <a-select :options="positionOptions" v-model="formData.position_id" placeholder="请选择职位" />
                    </a-form-item>
                </a-col>
            </a-row>


            {{ formData }}
        </template>

    </Popup>
</template>

<script setup lang="ts">
import { addAdmin, updateAdmin, getRoleList, getOrganizationList } from '@/api/system/auth/admin'
import { getDepartmentLists } from '@/api/system/organize/department'
import { getPositionLists } from '@/api/system/organize/position'
import Popup from '@/components/Popup/index.vue'
const popupRef = ref<InstanceType<typeof Popup>>()


const emits = defineEmits<{
    (e: 'success', data?: any): void
    (e: 'cancel'): void
}>()

const mode = ref<'add' | 'edit'>('add')
const modeTitle = computed(() => {
    return mode.value === 'add' ? '新增管理员' : '编辑管理员'
})

interface FormData {
    id?: number | null
    username: string
    password: string
    repassword: string
    nickname: string
    avatar: string
    role?: number[]
    status?: boolean

    organization_id: number | null
    department_id: number | null
    position_id: number | null
}
const formData = reactive<FormData>({
    id: null,
    username: '',
    password: '',
    repassword: '',
    nickname: '',
    avatar: '',
    role: [],
    status: true,
    organization_id: null,  
    department_id: null,
    position_id: null

})

const rules = {
    username: [{ required: true, message: '请输入管理员名称' }],

}


const open = (type: any) => {

    mode.value = type
    popupRef.value?.open()

    // popupRef.value?.setFormData(formData)

    request()
}

const roleOptions = ref<any[]>([])
const organizeOptions = ref<any[]>([])
const departmentOptions = ref<any[]>([])
const positionOptions = ref<any[]>([])
const request = async () => {

    // 获取角色列表
    const role = await getRoleList()
    roleOptions.value = role.map((item: any) => ({
        label: item.name,
        value: item.id,
        disabled: !item.status,
    }))

    // 获取组织架构列表
    const organize = await getOrganizationList()
    organizeOptions.value = organize.map((item: any) => ({
        label: item.name,
        value: item.id,
    }))
}

const handleDepartmentChange = async (value: string) => {
    departmentOptions.value = []
    formData.department_id = null
    formData.position_id = null
    const department = await getDepartmentLists({ organization_id: value })
    departmentOptions.value = department.map((item: any) => ({
        label: item.name,
        value: item.id,
    }))
}

const handlePositionChange = async (value: string) => {
    positionOptions.value = []
    formData.position_id = null
    const position = await getPositionLists({ department_id: value })
    positionOptions.value = position.map((item: any) => ({
        label: item.name,
        value: item.id,
    }))
}

const handleSubmit = async (data: FormData) => {
    try {
        mode.value === 'add' ? await addAdmin(data) : await updateAdmin(data)
        await popupRef.value?.close()
        popupRef.value?.closeLoading()
        emits('success', data)
    } catch (error) {
        popupRef.value?.closeLoading()
    }
}

const setFormData = async (record: Record<any, any>) => {
    if (record) {
        console.log(record.info)
        // 使用解构赋值来合并数据
        const { info, ...rest } = record
        for (const key in formData) {
            if (rest[key] != null && rest[key] != undefined) {
                //@ts-ignore
                formData[key] = rest[key]
            }
        }

        formData.organization_id = info.organization_id || null
        if (info.department_id) {
            handleDepartmentChange(info.organization_id)
            formData.department_id = info.department_id
            if (info.position_id) {
                handlePositionChange(info.department_id)
                formData.position_id = info.position_id
            }
        }


        // Object.assign(formData, rest)
        // 确保弹窗组件也更新了数据
        nextTick(() => {
            popupRef.value?.setFormData(formData)
        })
    }

}


const handleCancel = async () => {
    departmentOptions.value = []
    positionOptions.value = []
    await popupRef.value?.close()
    emits('cancel')
}
defineExpose({
    open,
    setFormData
})
</script>

<style scoped lang="scss"></style>
